'use server'

import {getAccessToken} from "@/lib/actions";

export async function getObj(url: string): Promise<any> {
    const token = await getAccessToken();
    try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}${url}`, {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            }
        })
        return  await response.json();
    } catch (err) {
        console.error('getObjError', err)
    }
}

export async function postObj(url: string, data: any): Promise<any> {
    const token = await getAccessToken();
    try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}${url}`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
            },
            body: data,

        })
        return  await response.json();

    } catch (err) {
        console.error('postObjError', err)
    }
}

export async function patchObj(url: string, data: any): Promise<any> {
    const token = await getAccessToken();
    try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}${url}`, {
            method: 'PATCH',
            headers: {
                'Authorization': `Bearer ${token}`,
            },
            body: data,
        })
        return  await response.json();

    } catch (err) {
        console.error('patchObjError', err)
    }
}

export async function deleteObj(url: string): Promise<any> {
    try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}${url}`)
        return  await response.json();

    } catch (err) {
        console.error('delObjError', err)
    }
}

export async function getObjWithoutToken(url: string): Promise<any> {
    try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}${url}`)
        return await response.json();

    } catch (err) {
        console.error('getObjWTError', err)
    }
}

export async function postObjWithoutToken(url: string, data: any): Promise<any> {
    try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}${url}`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: data,
        })
        return await response.json()

    } catch (err) {
        console.error('postObjWTError', err)
    }

}
